package com.gs.disk.service.admin.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gs.entity.GeneralPage;
import com.gs.common.util.ConvertUtils;
import com.gs.disk.dao.admin.RoleDao;
import com.gs.disk.dao.admin.UserDao;

import com.gs.disk.dao.common.MenuDao;
import com.gs.disk.dto.admin.RoleDto;
import com.gs.disk.dto.admin.UserDto;
import com.gs.entity.RoleEntity;
import com.gs.entity.UserEntity;
import com.gs.disk.service.admin.UserService;
import com.gs.disk.service.common.RoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao dao;

    @Resource
    private RoleDao roleDao;

    @Resource
    private RoleService roleService;

    @Resource
    private MenuDao menuDao;


    /**
     * 查询所有记录
     * @param userName 用户名
     * @return 返回集合，没有返回空List
     */
    @Override
    public List<UserEntity> search(String userName) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.like("nick_name", userName);
    	return dao.selectList(wrapper);
    }


    /**
     * 根据主键查询
     *
     * @param uid 主键
     * @return 返回记录，没有返回null
     */
    @Override
    public UserEntity getById(Long uid) {
        return dao.selectById(uid);
    }

    /**
     * 用户是否存在
     * @param email 邮箱
     * @return
     */
    @Override
    public Boolean existByEmail(String email) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("mail", email);

        Integer count = dao.selectCount(wrapper);
        return count != 0;
    }

    /**
     * 用户是否存在
     * @param phone 手机号
     * @return
     */
    @Override
    public Boolean existByPhone(String phone) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);

        Integer count = dao.selectCount(wrapper);
        return count != 0;
    }

    /**
     * 根据用户名查询用户
     * @param userName 用户名
     * @return
     */
    @Override
    public UserEntity getByUserName(String userName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("name",userName);
        return dao.selectOne(wrapper);
    }


    /**
     * 得到role集合
     * @param name 用户名
     * @return
     */
    @Override
    public Set<RoleDto> getRole(String name) {
        QueryWrapper<RoleEntity> wrapper = new QueryWrapper<RoleEntity>();
        wrapper.eq("role_name", name);
        return new HashSet(ConvertUtils.sourceToTarget(roleDao.selectList(wrapper), RoleDto.class));
    }

    @Override
    public List<String> getUserMenuList(String name) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id, permissions,role_ids");// 不查id可能会空指针异常
        wrapper.eq("name", name);
        // 获取用户信息
        UserEntity userEntity = dao.selectOne(wrapper);
        List<String> menuList = new LinkedList<>();

        String permissions = userEntity.getPermissions();
        // 如果没有皇帝圣旨, 那就做好本职工作
        if(ObjectUtil.isEmpty(permissions)) {
            String roleIds = userEntity.getRoleIds();
            if(ObjectUtil.isNotNull(roleIds)) {
                String[] roleId = roleIds.split(",");
                menuList.addAll(roleDao.getMenuList(roleId));
            }
        } else {
            // 如果圣旨在手, 让你干什么就干什么
            String[] split = permissions.split(",");
            menuList.addAll(Arrays.asList(split));
        }

        return menuList;
    }


    /**
     * 获取用户的权限
     * @param name 用户名
     * @return
     */
    @Override
    public Set<String> getUserRolePermission(String name) {

        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id, permissions,role_ids");// 不查id可能会空指针异常
        wrapper.eq("name", name);

        // 获取用户信息
        UserEntity userEntity = dao.selectOne(wrapper);
        Set<String> permissionSet = new HashSet<>();

        String permissions = userEntity.getPermissions();
        // 如果没有皇帝圣旨, 那就做好本职工作
        if(ObjectUtil.isEmpty(permissions)) {
            String roleIds = userEntity.getRoleIds();
            if(ObjectUtil.isNotNull(roleIds)) {
                String[] roleId = roleIds.split(",");
                List<String> menuList = roleDao.getMenuList(roleId);
                permissionSet.addAll(menuDao.listPermissionSet(menuList));

            }
        } else {
            // 如果圣旨在手, 让你干什么就干什么
            String[] split = permissions.split(",");
            permissionSet.addAll(menuDao.listPermissionSet(Arrays.asList(split)));
        }


        return permissionSet;
    }

    /**
     * 插入或更新用户
     * @param user 用户
     * @return
     */
    @Override
    public Integer save(UserEntity user) {
        int i = 0;
        if(user.getId() == null) {
            i = dao.insert(user);
        }else {
            i = dao.updateById(user);
        }
        return 1;
    }

    /**
     * 删除记录
     *
     * @param uid 用户id
     * @return 返回影响行数
     */
    @Override
    public Integer delete(Long uid) {
    	return dao.deleteById(uid);
    }

    /**
     * 获取加密后的密码
     * @param username
     * @return
     */
    @Override
    public String getPassword(String username) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("name", username);
        UserEntity user = dao.selectOne(wrapper);

        if(ObjectUtil.isNotNull(user)) {
            String password = user.getEncodePassword();
            return password;
        }
        return null;
    }

    @Override
    public void updatePermissions(Long userId, List<String> permissionList) {
        StringJoiner sj = new StringJoiner(",");
        permissionList.stream().forEach(sj::add);
        UserEntity userEntity = new UserEntity();
        userEntity.setId(userId);
        userEntity.setPermissions(sj.toString());
        dao.updateById(userEntity);
    }

    @Override
    public GeneralPage<UserDto> getUserList(Map<String, Object> map) {
        Object name = map.get("name");
        Object email = map.get("email");
        Object pageSize = map.get("pageSize");
        Object page = map.get("page");

        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(name)) {
            wrapper.like("name", name);
        }
        if(ObjectUtil.isNotEmpty(email)) {
            wrapper.like("email", email);
        }

        Page page1 = dao.selectPage(new Page(Convert.toInt(page), Convert.toInt(pageSize)), wrapper);

        GeneralPage generalPage = new GeneralPage();

        List<UserDto> resultList = new LinkedList<>();
        page1.getRecords().forEach(e -> {
            UserEntity userEntity = (UserEntity) e;
            UserDto userDto = ConvertUtils.sourceToTarget(userEntity, UserDto.class);
            // 获取用户角色
            List<String> roleName = roleService.roleNameList(userEntity.getId());
            userDto.setRoleNameList(roleName);
            // 获取用户菜单
            List<String> menuList = getUserMenuList(userDto.getName());
            userDto.setMenus(menuList);
            // 获取用户权限
            Set<String> rolePermissionSet = getUserRolePermission(userDto.getName());
            userDto.setPermissions(rolePermissionSet);
            resultList.add(userDto);
        });
        generalPage.setList(resultList);

        Integer total = dao.selectCount(wrapper);
        generalPage.setTotal(total);
        return generalPage;
    }

}